package com.joysuch.wwyt.patrol.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.service.BaseImageRepositoryService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.repository.MhMonitoringPointDao;
import com.joysuch.wwyt.patrol.entity.PatrolDataType;
import com.joysuch.wwyt.patrol.entity.PatrolOption;
import com.joysuch.wwyt.patrol.entity.bean.*;
import com.joysuch.wwyt.patrol.entity.dto.PatrolDataTypeDto;
import com.joysuch.wwyt.patrol.entity.dto.PatrolOptionDto;
import com.joysuch.wwyt.patrol.entity.vo.PatrolDataTypeVo;
import com.joysuch.wwyt.patrol.mapper.PatrolCheckItemMapper;
import com.joysuch.wwyt.patrol.mapper.PatrolDataTypeMapper;
import com.joysuch.wwyt.patrol.mapper.PatrolOptionMapper;
import com.joysuch.wwyt.patrol.service.PatrolCheckItemService;
import com.joysuch.wwyt.patrol.service.PatrolDataTypeService;
import com.joysuch.wwyt.patrol.service.PatrolOptionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lrf
 * @since 2022-03-01
 */
@Service
public class PatrolDataTypeServiceImpl extends ServiceImpl<PatrolDataTypeMapper, PatrolDataType> implements PatrolDataTypeService {

    @Autowired
    private PatrolDataTypeMapper patrolDataTypeMapper;
    @Autowired
    private PatrolOptionService patrolOptionService;
    @Autowired
    private PatrolOptionMapper patrolOptionMapper;
    @Autowired
    private PatrolCheckItemMapper patrolCheckItemMapper;
    @Autowired
    private PatrolCheckItemService patrolCheckItemService;
    @Autowired
    private BaseImageRepositoryService imageRepositoryService;
    @Autowired
    private PatrolDataTypeService patrolDataTypeService;
    @Autowired
    private MhMonitoringPointDao mhMonitoringPointDao;

    @Override
    public Page<PatrolDataTypeDto> findDataTypePageList(PatrolDataTypeSearchBean dataTypeSearchBean) {
        Page<PatrolDataTypeDto> page = new Page<>(dataTypeSearchBean.getPageNo() + 1, dataTypeSearchBean.getPageSize());
        dataTypeSearchBean.setOrgCode(Context.getCompanyCode());
        dataTypeSearchBean.setTenentId(Context.getCurrentTenantId());
        Page<PatrolDataTypeDto> dateTypePage = patrolDataTypeMapper.findDataTypePageList(page,dataTypeSearchBean);

        List<PatrolDataTypeDto> dateTypeRecords = dateTypePage.getRecords();
        dateTypeRecords.forEach(each -> {
           List<PatrolOptionVo> optionList =  patrolDataTypeMapper.findOptionById(each.getId());
            if(each.getSingletonChoiceFlag().equals("0")){
               each.setSingletonChoiceFlag("单选");
           }else if(each.getSingletonChoiceFlag().equals("1")){
               each.setSingletonChoiceFlag("多选");
           }
            each.setList(optionList);
            String optionsStr = optionList.stream().map(PatrolOptionVo::getOptionUnit).collect(Collectors.joining(Constant.SPLIT_COMMA));
            each.setOptionsOrUnit(optionsStr);
        });
        return dateTypePage;
    }

    @Override
    public boolean saveDataType(PatrolDataTypeVo dataTypeVo) throws ApiBusinessException {
        //判断是否有重名,
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        Long count =  patrolDataTypeMapper.judgeForName(dataTypeVo.getDataName(),tenentId,orgCode,dataTypeVo.getId());
        if (0 != count){
            throw new ApiBusinessException(Status.NAME_WAS_EXIST,dataTypeVo.getDataName());
        }
        ArrayList<String> sameName = new ArrayList<>();
        List<PatrolOptionVo> optionListPage = dataTypeVo.getList();
        Map<String, List<PatrolOptionVo>> optionGroup = optionListPage.stream().collect(Collectors.groupingBy(PatrolOptionVo::getOptionUnit));
        optionGroup.entrySet().forEach(optionsEntry -> {

            if (optionsEntry.getValue().size() > 1) {
                sameName.add(optionsEntry.getKey());
            }
        });
        Assert.isTrue(CollectionUtils.isEmpty(sameName),String.format(Status.DATA_OPTION_NAME_REPEAT.getMsg(), sameName.stream().collect(Collectors.joining(Constant.SPLIT_COMMA))));

        //查看删除的选项是否被检查项目(检查点)绑定
        if (CollectionUtil.isNotEmpty(dataTypeVo.getDelIds())){
            String errMes = patrolCheckItemService.findPointByoptionId(dataTypeVo.getDelIds());
            if (StringUtils.isNotBlank(errMes)){
                throw new ApiBusinessException(Status.DATA_OPTION_BIND_POINT,errMes);
            }
        }
        PatrolDataType dataType=new PatrolDataType();
        dataType.setId(dataTypeVo.getId());
        dataType.setDataType("1");
        dataType.setDataName(dataTypeVo.getDataName());
        dataType.setSingletonChoiceFlag(dataTypeVo.getSingletonChoiceFlag());
        boolean saved = saveOrUpdate(dataType);
        List<PatrolOptionVo> dataTypeList=dataTypeVo.getList();
        ArrayList<PatrolOption> optionList = new ArrayList<>();
        for (PatrolOptionVo e:dataTypeList) {
            PatrolOption option = new PatrolOption();
            option.setId(e.getId());
            option.setTypeId(dataType.getId());
            option.setOrderNo(e.getOrderNo());
            option.setOptionUnit(e.getOptionUnit());
            optionList.add(option);
        }
        if(CollectionUtil.isNotEmpty(optionList)){
            patrolOptionService.saveOrUpdateBatch(optionList);
        }
        patrolOptionService.deleteByIds(dataTypeVo.getDelIds());
        return saved;
    }

    @Override
    public int deleteDataTypeId(Long id) throws ApiBusinessException {
        //判断该数据类型有没有被检查项目(检查点)使用
        List<String> pointNameList =  patrolCheckItemMapper.findByDataTypeId(id,Context.getCurrentTenantId(),Context.getCurrentOrgCode());
        if (CollectionUtil.isNotEmpty(pointNameList)){
            String pointNames = pointNameList.stream().map(Object::toString).collect(Collectors.joining(Constant.SPLIT_COMMA));
            throw new ApiBusinessException(Status.DATA_TYPE_BIND_POINT,pointNames);
        }
        return patrolDataTypeMapper.deleteDataTypeId(id);
    }

    @Override
    public Page<PatrolOptionDto> findOptionPage( PatrolOptionSearchBean dataTypeSearchBean) {
        dataTypeSearchBean.setOrgCode(Context.getCompanyCode());
        dataTypeSearchBean.setTenentId(Context.getCurrentTenantId());
        Page<PatrolOptionDto> page = new Page<>(dataTypeSearchBean.getPageNo() + 1 ,dataTypeSearchBean.getPageSize());
        Page<PatrolOptionDto> list = patrolDataTypeMapper.findOptionPage(page,dataTypeSearchBean.getName(),dataTypeSearchBean.getAttribute(),dataTypeSearchBean.getTenentId(),dataTypeSearchBean.getOrgCode());
        if(CollectionUtil.isNotEmpty(list.getRecords())){
            list.getRecords().forEach(each ->{
                int count = mhMonitoringPointDao.countByMonitoringTypeIdAndShowState(each.getId());
                List<String> errMes = patrolCheckItemMapper.getPointByTypeId(each.getId(),Context.getCurrentTenantId(),Context.getCurrentOrgCode());
                if (count==0&&CollectionUtils.isEmpty(errMes)){
                    each.setCanDelete(1);
                }else{
                    each.setCanDelete(0);
                }
                if(each.getCategoryId() == 0){
                    each.setCategoryName("设备监测点");
                }else if(each.getCategoryId() ==1){
                    each.setCategoryName("环境监测点");
                }
                if ( null != each.getImageId()){
                    each.setImageBean(imageRepositoryService.findBeanById(each.getImageId()));
                }
            });
        }

        return list;
    }

    @Override
    public List<SimpleListDataType> getSimpleList() {
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        return patrolDataTypeMapper.getSimpleList(tenentId,orgCode);
    }

    @Override
    public List<SimpleListDataType> getSimpleListShocks() {
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        return patrolDataTypeMapper.getSimpleListShocks(tenentId,orgCode);
    }

    @Override
    public List<SimpleListDataType> getSimpleListShock() {
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        return patrolDataTypeMapper.getSimpleListShock(tenentId,orgCode);
    }

    @Override
    public List<String> findOptionByTypeId(Long dataTypeId) {
        return patrolOptionMapper.findOptionByTypeId(dataTypeId);
    }

    @Override
    public List<ExcelItemBean> getExcelItemList() {
        return patrolOptionMapper.getExcelItemList(Context.getCurrentTenantId(),Context.getCurrentOrgCode());
    }
}
